package m3;

import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.Random;
import java.util.Scanner;

/**
 * @author  郭鲁政
 */
public class Producer {
    public static void main(String[] args)throws Exception {
        TransactionMQProducer p = new TransactionMQProducer("prod-group3");
        p.setNamesrvAddr("192.168.64.141:9876");
        p.setTransactionListener(new TransactionListener() {
            @Override
            public LocalTransactionState executeLocalTransaction(Message message, Object o) {
                System.out.println("执行本地业务,参数"+args);
                /**
                 *    COMMIT_MESSAGE, 提交
                 *     ROLLBACK_MESSAGE, 回滚
                 *     UNKNOW; 不知道
                 */
            if (Math.random()<0.5){
                System.out.println("本地业务执行成功");
                return LocalTransactionState.COMMIT_MESSAGE;//提交消息
            }else {
                System.out.println("本地业务执行失败");
                return LocalTransactionState.ROLLBACK_MESSAGE;
            }
            }

            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
                System.out.println("rocketMQ正在执行回查");
                return LocalTransactionState.UNKNOW;
            }
        });
        p.start();
        while (true) {
            System.out.println("请输入消息");
            String next = new Scanner(System.in).next();
            Message msg = new Message("Topic3", next.getBytes());
            TransactionSendResult r = p.sendMessageInTransaction(msg, "业务数据参数");
            System.out.println("返回结果"+r);
        }
    }
}
